package com.yuanfeng.activity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yuanfeng.activity.dto.PromotionIndexQueryParamDTO;
import com.yuanfeng.activity.dto.SeckillGoodsUpdateDTO;
import com.yuanfeng.activity.dto.SecondKillGoodsDTO;
import com.yuanfeng.activity.entity.ActivitySeckillBaseEntity;
import com.yuanfeng.activity.entity.ActivitySeckillGoodsEntity;
import com.yuanfeng.activity.mapper.ActivitySeckillBaseMapper;
import com.yuanfeng.activity.mapper.ActivitySeckillGoodsMapper;
import com.yuanfeng.activity.service.ActivitySeckillGoodsService;
import com.yuanfeng.activity.vo.*;
import com.yuanfeng.commoms.aspect.UserPermissionsResult;
import com.yuanfeng.commoms.aspect.UserService;
import com.yuanfeng.commoms.config.PermissionsConstant;
import com.yuanfeng.commoms.dto.goods.AppSeckillGoodsVO;
import com.yuanfeng.commoms.dto.goods.SeckillGoodsDTO;
import com.yuanfeng.commoms.dto.goods.SeckillGoodsListDTO;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.DateUtils;
import com.yuanfeng.commoms.util.ParseMapUtils;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.util.excel.ExcelsUtil;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.vo.activity.AppSeckillGoodsQueryResultVO;
import com.yuanfeng.commoms.vo.activity.CheckSeckillLimitResultVO;
import com.yuanfeng.commoms.vo.activity.ModularGoodsVO;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName ActivitySeckillGoodsServiceImpl
 * @Description 限时秒杀商品表
 * @Author cyp
 * @Date 2023-05-25 13:58:28
 * @Version 1.0
 **/
@Service
public class ActivitySeckillGoodsServiceImpl extends ServiceImpl<ActivitySeckillGoodsMapper, ActivitySeckillGoodsEntity>
        implements ActivitySeckillGoodsService {

    @Autowired
    private ActivitySeckillBaseMapper activitySeckillBaseMapper;
    @Override
    public AppSeckillGoodsQueryResultVO selectSeckillByGoodsId(Map<String, Object> map) {
       return this.baseMapper.selectSeckillByGoodsId(map);
    }

    @Override
    public AppSeckillGoodsQueryResultVO selectSeckillByGoodsId2(Integer goodsId) {
        return this.baseMapper.selectSeckillByGoodsId2(goodsId);
    }

    @Override
    public AppSeckillGoodsVO selectByGoodsId(Integer goodsId) {
        return this.baseMapper.selectByGoodsId(goodsId);
    }

    @Override
    public ResponseResult seckillCheckLimit(Map<String, Object> param) {
        ResponseResult rr = new ResponseResult();
        String userId = null;
        if(null != param.get("token")){
            String token = (String) param.get("token");
            UserInfoVO userInfo = ParseTokenUtils.getUserInfoByTokenNoIsExist(token);
            if (null != userInfo) {
                userId = userInfo.getUserId();
            }
        }
        Integer goodsId = (Integer) param.get("goodsId");
        Integer commonId = (Integer) param.get("commonId");
        CheckSeckillLimitVO data = this.baseMapper.querySeckillInfo(param);
        Integer count = null;
        if(null != data){
            Integer goodsUpperLimit = data.getGoodsUpperLimit();
            if( 0 == goodsUpperLimit){
                rr.setCode(1);
                rr.setData(null);
                rr.setMessage("该商品不限购");
                return rr;
            }
            param.put("goodsStartTime",data.getGoodsStartTime());
            param.put("goodsEndTime",data.getGoodsEndTime());
            param.put("goodsId", goodsId);
            param.put("commonId", commonId);
            param.put("userId", userId);
            param.put("seckillId", data.getSeckillId());
            if(null != userId){
                count = this.baseMapper.queryOrderGoodsCount(param);
            }
            count = count==null?0:count;
            data.setBuyNum(count);
            if(count >= goodsUpperLimit){
                rr.setCode(2);
                rr.setData(count);
                rr.setMessage("该商品已达购买上限,继续购买将以原价进行购买，是否继续");
            }else{
                rr.setCode(1);
                rr.setData(count);
                rr.setMessage("未达上限，可以购买");
            }

        }else{
            rr.setCode(2);
            rr.setMessage("活动未开始或活动已结束，需原价购买");
        }

        return rr;
    }

    @Override
    public CheckSeckillLimitResultVO querySeckillInfoByGoodsId(Integer goodsId) {
        return this.baseMapper.querySeckillInfoByGoodsId(goodsId);
    }

    @Override
    public Integer querySeckillNum(Map<String, Object> paramMap) {
        return this.baseMapper.querySeckillNum(paramMap);
    }

    @Override
    public ResponseResult updateSaleForSeckill(Map<String, Object> paramMap) {
        this.baseMapper.updateSaleForSeckill(paramMap);
        return ResponseResult.success();
    }

    @Override
    public ResponseResult querySeckillIndex(PromotionIndexQueryParamDTO param) {
        SeckillIndexResultVO result = new SeckillIndexResultVO();

        try {
            Date today = new Date();
            // 演示站数据
            Date goodsStartTime = DateUtils.parseDateTime("2020-02-02 00:00:00");
            // 演示站屏蔽
            // Date goodsStartTime = param.getGoodsStartTime();
            Date goodsStartTime2 = goodsStartTime;
            List<SeckillGoodsListQueryResultVO> promotionGoodsList = new ArrayList<>();
            Integer totalCount = 0;
            Long actOverplusTime;
            //活动还未开始
            if(today.before(goodsStartTime)){
                //将对象转换为map
                Map data = ParseMapUtils.beanToMap(param);
                //分页查询数据
                IPage<SeckillGoodsListQueryResultVO> page = this.baseMapper.selectSeckillIndexGoods(new Query<SeckillGoodsListQueryResultVO>().getPage(data),param);
                promotionGoodsList = page.getRecords();
                totalCount = PageUtils.getPage(page).getTotalCount();
                actOverplusTime = DateUtils.getSecondByMinusDate(new Date(),goodsStartTime);
                result.setActState(0);
                //活动已开始
            }else{
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Calendar cal = Calendar.getInstance();
                cal.setTime(today);
                // 演示站数据
                cal.add(Calendar.YEAR, -24);
                // 演示站屏蔽
                // cal.add(Calendar.HOUR, -24);
                goodsStartTime = cal.getTime();
                param.setGoodsStartTime(goodsStartTime);
                //将对象转换为map
                Map data = ParseMapUtils.beanToMap(param);
                //分页查询数据
                IPage<SeckillGoodsListQueryResultVO> page = this.baseMapper.selectSeckillIndexGoods2(new Query<SeckillGoodsListQueryResultVO>().getPage(data),param);
                promotionGoodsList = page.getRecords();
                totalCount = PageUtils.getPage(page).getTotalCount();

                Date goodsEndTime = new Date();
                cal.setTime(goodsStartTime2);
                if(sdf.format(goodsStartTime2).contains("00:00:00")){
                    cal.add(Calendar.HOUR, 8);
                }else {
                    cal.add(Calendar.HOUR, 4);
                }
                goodsEndTime = cal.getTime();
                actOverplusTime = DateUtils.getSecondByMinusDate(new Date(),goodsEndTime );
                result.setActState(1);
            }


            if (!CollectionUtils.isEmpty(promotionGoodsList)) {
                for (SeckillGoodsListQueryResultVO promotionGoods : promotionGoodsList) {
                    // 剩余时间
                    Long overplusTime = DateUtils.getSecondByMinusDate(new Date(), promotionGoods.getGoodsEndTime());
                    // 判断是否开始
                    if (DateUtils.compareDate2(promotionGoods.getGoodsStartTime())) {
                        overplusTime = DateUtils.getSecondByMinusDate(new Date(), promotionGoods.getGoodsStartTime());
                        promotionGoods.setActivityStartStatus(0);
                    } else {
                        promotionGoods.setActivityStartStatus(1);
                    }
                    promotionGoods.setOverplusTime(overplusTime);

                    String userId = null;
                    if(null != param.getToken()){
                        String token = param.getToken();
                        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByTokenNoIsExist(token);
                        if (null != userInfo) {
                            userId = userInfo.getUserId();
                        }
                    }
                    Map<String, Object> map = new HashMap<>();
                    Integer goodsId = promotionGoods.getGoodsId();
                    Integer commonId = promotionGoods.getCommonId();
                    map.put("goodsId", goodsId);
                    map.put("commonId", commonId);
                    map.put("userId", userId);
                    CheckSeckillLimitVO data = this.baseMapper.querySeckillInfo(map);
                    Integer count = 0;
                    if (null != data) {
                        map.put("goodsStartTime", data.getGoodsStartTime());
                        map.put("goodsEndTime", data.getGoodsEndTime());
                        if(null != userId){
                            count = this.baseMapper.queryOrderGoodsCount(map);
                        }
                    }
                    promotionGoods.setBuyNum(count);
                }
            } else {
                promotionGoodsList = Lists.newArrayList();
            }

            result.setTotalCount(totalCount);
            result.setPromotionGoodsList(promotionGoodsList);
            result.setActOverplusTime(actOverplusTime);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ResponseResult.success(result);
    }

    @Override
    public ResponseResult checkSeckillLimit(Map<String, Object> param) {
        String userId = null;
        if(null != param.get("token")){
            String token = (String) param.get("token");
            UserInfoVO userInfo = ParseTokenUtils.getUserInfoByTokenNoIsExist(token);
            if (null != userInfo) {
                userId = userInfo.getUserId();
            }
        }
        Integer goodsId = (Integer) param.get("goodsId");
        Integer commonId = (Integer) param.get("commonId");
        CheckSeckillLimitVO data = this.baseMapper.querySeckillInfo(param);
        Integer count = null;
        if (null != data) {
            param.put("goodsStartTime", data.getGoodsStartTime());
            param.put("goodsEndTime", data.getGoodsEndTime());
            param.put("goodsId", goodsId);
            param.put("commonId", commonId);
            param.put("userId", userId);
            param.put("seckillId", data.getSeckillId());
            if(null != userId){
                count = this.baseMapper.queryOrderGoodsCount(param);
            }
            count = count == null ? 0 : count;
            data.setBuyNum(count);
            return ResponseResult.success(BizCodeEnume.ACTIVITY_NO_PURCHASE_LIMIT.getMsg(),data);
        } else {
            return ResponseResult.fail(BizCodeEnume.ACTIVITY_ACTIVITY_ENDED.getCode(), BizCodeEnume.ACTIVITY_ACTIVITY_ENDED.getMsg());
        }

    }
    @Override
    public ResponseResult inactiveShopSeckillBase(Map<String, Object> paramMap) {

        List<Integer> commonIdList = this.baseMapper.selectList(new LambdaQueryWrapper<ActivitySeckillGoodsEntity>()
                                    .eq(ActivitySeckillGoodsEntity::getSeckillId,Integer.valueOf(paramMap.get("seckillId").toString())))
                                    .stream().map(ActivitySeckillGoodsEntity::getCommonId).collect(Collectors.toList());

        if (!CollectionUtils.isEmpty(commonIdList)) {
            this.baseMapper.updateCommonIsXian2(commonIdList);
        }
        this.baseMapper.update(null,new LambdaUpdateWrapper<ActivitySeckillGoodsEntity>()
                       .set(ActivitySeckillGoodsEntity::getSeckillGoodsState,3)
                       .eq(ActivitySeckillGoodsEntity::getSeckillId,Integer.valueOf(paramMap.get("seckillId").toString())));

        activitySeckillBaseMapper.update(null,new LambdaUpdateWrapper<ActivitySeckillBaseEntity>()
                .set(ActivitySeckillBaseEntity::getSeckillState,3)
                .eq(ActivitySeckillBaseEntity::getSeckillId,Integer.valueOf(paramMap.get("seckillId").toString())));

        return ResponseResult.success();
    }

    @Override
    public ResponseResult seckillGoodsPrice(Integer goodsId) {
        ModularGoodsVO modularGoodsVO = this.baseMapper.seckillGoodsPrice(goodsId);
        return ResponseResult.success(modularGoodsVO);
    }

    @Override
    public ResponseResult querySecondKillGoods(SecondKillGoodsDTO param) throws IllegalAccessException {
        Map data= ParseMapUtils.beanToMap(param);
        IPage<ActivitySeckillGoodsEntity> page=this.page(new Query<ActivitySeckillGoodsEntity>().getPage(data),
                new LambdaQueryWrapper<ActivitySeckillGoodsEntity>().eq(ActivitySeckillGoodsEntity::getSeckillId, param.getSeckillId()));
        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult querySeckillDiffer(PromotionIndexQueryParamDTO param) {
        List<SeckillGoodsListQueryResultVO> seckillGoodsList = this.baseMapper.querySeckillDiffer(param);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        Date endTime = calendar.getTime();
        calendar.add(Calendar.YEAR,-1);
        Date startTime = calendar.getTime();
        String endDateTime = sdf.format(endTime);
        String startDateTime = sdf.format(startTime);
        Map map = new HashMap<>();
        map.put("endDateTime",endDateTime);
        map.put("startDateTime",startDateTime);
        if (seckillGoodsList == null ){
            //按商品销量查询20个
            List<Integer> integers = this.baseMapper.querySeckillGoodsHot(map);
            Map map1 = new HashMap<>();
            map1.put("goodsList",integers);
            if (integers != null && integers.size()>0) {
                List<SeckillGoodsListQueryResultVO> queryResults = this.baseMapper.querySeckillDifferHot(map1);
                seckillGoodsList.addAll(queryResults);
            }
        }else if(seckillGoodsList.size() < 20){
            List<Integer> integers = this.baseMapper.querySeckillGoodsHot(map);
            Map map1 = new HashMap<>();
            map1.put("goodsList",integers);
            if (integers != null && integers.size()>0) {
                List<SeckillGoodsListQueryResultVO> queryResults = this.baseMapper.querySeckillDifferHot(map1);
                for (SeckillGoodsListQueryResultVO queryResult : queryResults) {
                    boolean contains = seckillGoodsList.contains(queryResult);
                    if (!contains){
                        seckillGoodsList.add(queryResult);
                    }
                }
            }
            if (seckillGoodsList.size() > 20){
                seckillGoodsList.subList(0,20);
            }
        }
        return ResponseResult.success(seckillGoodsList);
    }

    @Override
    public ResponseResult queryDiscountBaseDataExp(Map<String, Object> param) {
        String[] title = {"商品名称", "规格", "付款商品件数", "总成交额", "新客户下单数", "老客户下单数"};
        List<Map<String, String>> list = Lists.newArrayList();


        List<SeckillDataVO> dataList = new ArrayList<>();
        Integer allGoodsCount = 0;
        BigDecimal allDealAmount = BigDecimal.ZERO;
        Integer allNewerOrderNum = 0;
        Integer allOlderOrderNum = 0;
        IPage<AppSeckillGoodsQueryResultVO> page=this.baseMapper.querySeckillGoodsInfo(new Query<AppSeckillGoodsQueryResultVO>().getPage(param),
                param);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        Date startTime = calendar.getTime();
        calendar.add(Calendar.DATE,-1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);


        if(null != page && page.getRecords().size()>0){
            for(AppSeckillGoodsQueryResultVO seckillGoodsListResult:page.getRecords()){
                seckillGoodsListResult.setGoodsSpec(seckillGoodsListResult.getSpecValueName());
                Map<Integer,Integer> newerNumMap = new HashMap<>();
                Map<Integer,Integer> olderNumMap = new HashMap<>();
                Integer goodsId = seckillGoodsListResult.getGoodsId();
                SeckillDataVO data = new SeckillDataVO();
                data.setGoodsName(seckillGoodsListResult.getGoodsName());
                data.setSpecName(seckillGoodsListResult.getGoodsSpec());
                if (calendar.getTime().before(seckillGoodsListResult.getStartDateTime())){
                    seckillGoodsListResult.setEndDateTime(seckillGoodsListResult.getStartDateTime());
                }else {
                    seckillGoodsListResult.setEndDateTime(calendar.getTime());
                }
                seckillGoodsListResult.setStartDateTime(startTime);
                SeckillGoodsInfoVO discountGoodsInfo = this.baseMapper.querySeckillGoodsInfo2(seckillGoodsListResult);
                if(null != discountGoodsInfo){
                    data.setDealAmount(discountGoodsInfo.getDealAmount());
                    data.setGoodsNum(discountGoodsInfo.getGoodsNum());
                    allGoodsCount = allGoodsCount + discountGoodsInfo.getGoodsNum();
                    allDealAmount = allDealAmount.add(discountGoodsInfo.getDealAmount());
                }else{
                    data.setDealAmount(BigDecimal.ZERO);
                    data.setGoodsNum(0);
                }
                List<String> buyerUserIds = this.baseMapper.queryBuyerUsers(seckillGoodsListResult);
                for(String userId:buyerUserIds) {
                    Map<String, Object> paramMap = new HashMap<>();
                    paramMap.put("userId", userId);
                    paramMap.put("startDateTime", seckillGoodsListResult.getStartDateTime());
                    paramMap.put("shopId",seckillGoodsListResult.getShopId());
                    paramMap.put("endDateTime",seckillGoodsListResult.getEndDateTime());
                    paramMap.put("goodsId",seckillGoodsListResult.getGoodsId());
                    paramMap.put("seckillPrice",seckillGoodsListResult.getSeckillPrice());

                    Integer olderCount = this.baseMapper.queryCountForOlder(paramMap);
                    Integer orderCount = this.baseMapper.queryUserOrderCount(paramMap);
                    if (null != olderCount) {
                        //新客
                        if (0 == olderCount) {
                            if(null == newerNumMap.get(goodsId)){
                                newerNumMap.put(goodsId,orderCount);
                            }else{
                                newerNumMap.put(goodsId,newerNumMap.get(goodsId)+orderCount);
                            }
                            allNewerOrderNum = allNewerOrderNum + orderCount;
                        } else {
                            if(null == olderNumMap.get(goodsId)){
                                olderNumMap.put(goodsId,orderCount);
                            }else{
                                olderNumMap.put(goodsId,olderNumMap.get(goodsId)+orderCount);
                            }
                            allOlderOrderNum = allOlderOrderNum + orderCount;
                        }
                    }
                }

                if(null != newerNumMap.get(goodsId)){
                    data.setNewerOrderNum(newerNumMap.get(goodsId));
                }else{
                    data.setNewerOrderNum(0);
                }

                if(null != olderNumMap.get(goodsId)){
                    data.setOlderOrderNum(olderNumMap.get(goodsId));
                }else{
                    data.setOlderOrderNum(0);
                }


                dataList.add(data);

            }

            for(SeckillDataVO data:dataList){
                HashMap<String, String> map = com.google.common.collect.Maps.newHashMap();
                map.put("商品名称", data.getGoodsName());
                map.put("规格", data.getSpecName());
                map.put("付款商品件数", data.getGoodsNum()+"");
                map.put("总成交额", data.getDealAmount()+"");
                map.put("新客户下单数", data.getNewerOrderNum()+"");
                map.put("老客户下单数", data.getOlderOrderNum()+"");


                list.add(map);

            }


            Map<String/* 此处的key为每个sheet的名称，一个excel中可能有多个sheet页 */, List<Map<String/* 此处key对应每一列的标题 */, String>>/*
             * 该list为每个sheet页的数据
             */> map = Maps
                    .newHashMap();
            map.put("测试合并数据", list);
            String url = ExcelsUtil.createExcel(title, map,
                    new int[]{0}/* 此处数组为需要合并的列，可能有的需求是只需要某些列里面相同内容合并 */);
            return ResponseResult.success(url);
        }else{
            return ResponseResult.fail(BizCodeEnume.NO_INFORMATION_OBTAINED);
        }
    }

    @Override
    public ResponseResult querySeckillBaseData(Map<String, Object> param) {
        if(null != param.get("seckillId")){
            Integer seckillId = (Integer) param.get("seckillId");

            List<SeckillDataVO> dataList = new ArrayList<>();
            Integer allGoodsCount = 0;
            BigDecimal allDealAmount = BigDecimal.ZERO;
            Integer allNewerOrderNum = 0;
            Integer allOlderOrderNum = 0;
            IPage<AppSeckillGoodsQueryResultVO> page=this.baseMapper.querySeckillGoodsInfo(new Query<AppSeckillGoodsQueryResultVO>().getPage(param),
                    param);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            Date startTime = calendar.getTime();
            calendar.add(Calendar.DATE,-1);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            if(null != page && page.getRecords().size()>0){
                for(AppSeckillGoodsQueryResultVO appSeckillGoodsResult:page.getRecords()){
                    Map<Integer,Integer> newerNumMap = new HashMap<>();
                    Map<Integer,Integer> olderNumMap = new HashMap<>();
                    Integer goodsId = appSeckillGoodsResult.getGoodsId();
                    SeckillDataVO data = new SeckillDataVO();
                    data.setGoodsName(appSeckillGoodsResult.getGoodsName());
                    data.setSpecName(appSeckillGoodsResult.getSpecValueName());
                    if (calendar.getTime().before(appSeckillGoodsResult.getStartDateTime())){
                        appSeckillGoodsResult.setEndDateTime(appSeckillGoodsResult.getStartDateTime());
                    }else {
                        appSeckillGoodsResult.setEndDateTime(calendar.getTime());
                    }
                    appSeckillGoodsResult.setStartDateTime(startTime);
                    SeckillGoodsInfoVO seckillGoodsInfo = this.baseMapper.querySeckillGoodsInfo2(appSeckillGoodsResult);
                    if(null != seckillGoodsInfo){
                        data.setDealAmount(seckillGoodsInfo.getDealAmount());
                        data.setGoodsNum(seckillGoodsInfo.getGoodsNum());
                        allGoodsCount = allGoodsCount + seckillGoodsInfo.getGoodsNum();
                        allDealAmount = allDealAmount.add(seckillGoodsInfo.getDealAmount());
                    }else{
                        data.setDealAmount(BigDecimal.ZERO);
                        data.setGoodsNum(0);
                    }
                    List<String> buyerUserIds = this.baseMapper.queryBuyerUsers(appSeckillGoodsResult);
                    for(String userId:buyerUserIds) {
                        Map<String, Object> paramMap = new HashMap<>();
                        paramMap.put("userId", userId);
                        paramMap.put("startDateTime", appSeckillGoodsResult.getStartDateTime());
                        paramMap.put("shopId",appSeckillGoodsResult.getShopId());
                        paramMap.put("endDateTime",appSeckillGoodsResult.getEndDateTime());
                        paramMap.put("goodsId",appSeckillGoodsResult.getGoodsId());
                        paramMap.put("seckillPrice",appSeckillGoodsResult.getSeckillPrice());

                        Integer olderCount = this.baseMapper.queryCountForOlder(paramMap);
                        Integer orderCount = this.baseMapper.queryUserOrderCount(paramMap);
                        if (null != olderCount) {
                            //新客
                            if (0 == olderCount) {
                                if(null == newerNumMap.get(goodsId)){
                                    newerNumMap.put(goodsId,orderCount);
                                }else{
                                    newerNumMap.put(goodsId,newerNumMap.get(goodsId)+orderCount);
                                }
                                allNewerOrderNum = allNewerOrderNum + orderCount;
                            } else {
                                if(null == olderNumMap.get(goodsId)){
                                    olderNumMap.put(goodsId,orderCount);
                                }else{
                                    olderNumMap.put(goodsId,olderNumMap.get(goodsId)+orderCount);
                                }
                                allOlderOrderNum = allOlderOrderNum + orderCount;
                            }
                        }
                    }

                    if(null != newerNumMap.get(goodsId)){
                        data.setNewerOrderNum(newerNumMap.get(goodsId));
                    }else{
                        data.setNewerOrderNum(0);
                    }

                    if(null != olderNumMap.get(goodsId)){
                        data.setOlderOrderNum(olderNumMap.get(goodsId));
                    }else{
                        data.setOlderOrderNum(0);
                    }


                    dataList.add(data);

                }
                Map<String, Object> result=new HashMap<>();
                result.put("dataEntityList",dataList);
                result.put("count",page.getTotal());
                result.put("allDealAmount",allDealAmount);
                result.put("allNewerOrderNum",allNewerOrderNum);
                result.put("allOlderOrderNum",allOlderOrderNum);
                result.put("allGoodsCount",allGoodsCount);

               return ResponseResult.success(result);

            }
            return ResponseResult.fail(BizCodeEnume.NO_INFORMATION_OBTAINED);
        }else{
            return ResponseResult.fail(BizCodeEnume.MISSING_PARAMETER);
        }

    }

    @Override
    public ResponseResult querySeckillGoodsSpecList(Map<String, Object> param) {

        if (null == param.get("commonId") || null == param.get("seckillId")) {
            return ResponseResult.fail(BizCodeEnume.MISSING_PARAMETER);
        }
        List<AppSeckillGoodsQueryResultVO> discountGoodsList = this.baseMapper.selectSeckillGoodsDetail2(param);

        if (CollectionUtils.isEmpty(discountGoodsList)) {
            discountGoodsList = Lists.newArrayList();
        }
        return ResponseResult.success(discountGoodsList);
    }

    @Override
    public ResponseResult deleteShopSeckillGoods(Map<String, Object> map) {
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(PermissionsConstant.SERLLER_PROMOTION_SECKILL, map.get("token").toString());

        if (userPermissionsResult.getFlag()) {

            // 更新商品表秒杀字段
            Integer commonIsXian = 0;// 2为 秒杀

            if (null != map.get("commonId")) {
                // 获取其他正在进行的活动
                List<Integer> activeCommonIdList = this.baseMapper.selectActiveSeckillGoods(map.get("seckillId").toString(),
                        map.get("commonId").toString());
                if (CollectionUtils.isEmpty(activeCommonIdList)) {
                    this.baseMapper.updateCommonIsXian(commonIsXian,  map.get("commonId").toString());
                }
            }
            this.baseMapper.deleteSeckillGoods2(map);
        } else {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
        return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
    }

    @Override
    public ResponseResult queryShopSeckillGoods(Map<String, Object> param) {
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(PermissionsConstant.SERLLER_PROMOTION_SECKILL, param.get("token").toString());

        if (userPermissionsResult.getFlag()) {

            ActivitySeckillGoodsEntity   result = this.baseMapper.selectById(param.get("seckillGoodsId").toString());
            return ResponseResult.success(result);
        } else {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }

    }

    @Override
    public ResponseResult addShopSeckillGoods(SeckillGoodsUpdateDTO param) {
        if (null == param.getSeckillId()) {
            return ResponseResult.fail(BizCodeEnume.MISSING_PARAMETER);
        }
        // 权限判断
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(param.getToken());

        if (userInfo != null) {
            List<SeckillGoodsListDTO> seckillGoodsList = param.getSeckillGoodsList();
            Integer shopId = Integer.valueOf(userInfo.getShopId());

            Integer commonId = null;
            // 查询店铺活动详情
            ActivitySeckillBaseEntity seckillBase = activitySeckillBaseMapper.selectById(param.getSeckillId());
            for (SeckillGoodsListDTO seckillGoods : seckillGoodsList) {
                List<SeckillGoodsDTO> specLists = seckillGoods.getSpecLists();
                if(null != specLists && specLists.size() >0 ){
                    for (SeckillGoodsDTO specList : specLists) {
                        //判断商品是否已存在 存在就不添加
                        Integer count = this.baseMapper.goodsIsRepetition(param.getSeckillId(),specList.getGoodsId());
                        if(null != count && count >0 ){
                            ResponseResult.fail(0, "商品已存在");
                        }
                        ActivitySeckillGoodsEntity addGoods = new ActivitySeckillGoodsEntity();
                        // 设置店铺活动参数
                        addGoods.setSeckillId(seckillBase.getSeckillId());
                        addGoods.setSeckillName(seckillBase.getSeckillName());
                        addGoods.setSeckillTitle(seckillBase.getSeckillTitle());
                        addGoods.setSeckillExplain(seckillBase.getSeckillExplain());
                        addGoods.setGoodsStartTime(seckillBase.getSeckillStartTime());
                        addGoods.setGoodsEndTime(seckillBase.getSeckillEndTime());
                        addGoods.setSeckillGoodsState(Integer.valueOf(seckillBase.getSeckillState()));
                        addGoods.setSeckillGoodsRecommend(seckillBase.getSeckillDoodsRecommend());
                        addGoods.setGoodsUpperLimit(seckillGoods.getGoodsUpperLimit());
                        addGoods.setGoodsLowerLimit(seckillBase.getSeckillLowerLimit());

                        commonId = seckillGoods.getCommonId();

                        addGoods.setGoodsId(specList.getGoodsId());
                        addGoods.setGoodsName(seckillGoods.getGoodsName());
                        addGoods.setGoodsImage(seckillGoods.getGoodsImage());
                        addGoods.setGoodsPrice(specList.getGoodsPrice().doubleValue());
                        addGoods.setSeckillNum(specList.getSeckillNum());
                        addGoods.setCommonId(commonId);
                        addGoods.setShopId(shopId);
                        addGoods.setSeckillPrice(specList.getSeckillPrice().doubleValue());
                        if (null == param.getSeckillGoodsId() || param.getSeckillGoodsId().equals("")) {
                            this.baseMapper.insert(addGoods);
                        } else {
                            addGoods.setSeckillGoodsId(param.getSeckillGoodsId());
                            this.baseMapper.updateById(addGoods);
                        }
                        if (null != commonId) {
                            // 更新显示折扣字段
                            Integer commonIsXian = 2;// 2为 秒杀
                            this.baseMapper.updateCommonIsXian(commonIsXian, commonId.toString());
                        }
                    }
                }
            }
        } else {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
        return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
    }

    @Override
    public ResponseResult queryGoodsList(Map<String, Object> param) {
        List<ActivitySeckillGoodsEntity> results = null;
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(String.valueOf(param.get("token")));

        if (userInfo != null) {
            //分页
            param.put("shopId",userInfo.getShopId());
            //分页查询数据
            IPage<ShopSeckillGoodsListVO> page = this.baseMapper.selectShopSeckillGoodsList(new Query<ShopSeckillGoodsListVO>().getPage(param),param);
            return ResponseResult.success(PageUtils.getPage(page));
        } else {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
    }
}

